import { APP_ENVIRONMENT_KEY } from '@/config/config';
import { userApi } from '@/services/api';
import AppEnvironments from '@/services/AppEnvironment';
import eventBus from '@/utils/eventBus';
import storage from '@/utils/storage';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import React, { useCallback, useState } from 'react';
import { FlatList, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Icon, useAppTheme } from 'tsun-smart-ui';

const AppEnvironmentScreen: React.FC = () => {
  const [selectedEnvironment, setSelectedEnvironment] =
    useState<AppEnvironments>(AppEnvironments.current);
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const appTheme = useAppTheme()

  const onConfirm = useCallback(() => {
    if (!selectedEnvironment) return;
    if (selectedEnvironment.baseURL == AppEnvironments.current.baseURL) return;
    AppEnvironments.current = selectedEnvironment;
    storage.setAsync(
      APP_ENVIRONMENT_KEY,
      JSON.stringify(selectedEnvironment.toJSON())
    );
    navigation.popToTop();
    eventBus.emit('LOGOUT_REQUIRED');
  }, [selectedEnvironment]);

  const renderItem = useCallback(
    ({ item }: { item: AppEnvironments }) => {
      const isSelected = selectedEnvironment?.baseURL == item.baseURL;
      return (
        <TouchableOpacity
          className="rounded-xl bg-text6 px-3 py-3 flex-row items-center"
          onPress={() => setSelectedEnvironment(item)}
        >
          <View className="flex-1 gap-2">
            <Text className="text-[18px] text-text1 font-medium">
              {item.name}
            </Text>
            <Text className="text-text2 text-[12px]">
              Base URL: {item.baseURL}
            </Text>
            <Text className="text-text2 text-[12px]">
              OSS URL: {item.ossURL}
            </Text>
          </View>
          {isSelected && <Icon name="check" size={24} color={appTheme.colors?.brand?.onPrimary} />}
        </TouchableOpacity>
      );
    },
    [selectedEnvironment]
  );

  return (
    <View className="flex-1">
      <FlatList
        data={AppEnvironments.allEnvironments}
        contentContainerClassName="p-4"
        renderItem={renderItem}
        ItemSeparatorComponent={ItemSeparator}
        keyExtractor={(item, index) => item.baseURL}
      />
      <SafeAreaView edges={[]} className="px-3 py-2 bg-text6 shadow-sm">
        <TouchableOpacity
          className="rounded-full items-center justify-center bg-brand1 py-4"
          onPress={onConfirm}
        >
          <Text className="text-white font-medium text-[16px]">确认</Text>
        </TouchableOpacity>
      </SafeAreaView>
    </View>
  );
};

export default AppEnvironmentScreen;

const ItemSeparator = React.memo(() => <View className="h-4" />);
